package org.jash.sportnews2109.vm

import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import org.jash.common.mvvm.BaseViewModel
import org.jash.common.retrofit
import org.jash.sportnews2109.dao.NewsDao
import org.jash.sportnews2109.dao.NewsDatabase
import org.jash.sportnews2109.entity.Category
import org.jash.sportnews2109.entity.News
import org.jash.sportnews2109.entity.Page
import org.jash.sportnews2109.net.APIService
import javax.inject.Inject

@HiltViewModel
class CategoryViewModel @Inject constructor(val newsDao: NewsDao):BaseViewModel() {
    val pageLiveData by lazy { MutableLiveData<Page<News>>() }
    val service by lazy { retrofit.create(APIService::class.java)}
    fun loadPage(type: Int, page: Int, size:Int) {
        progress(service.getNewsByCategoryId(type, page, size)) {
            if(it.code == 0) {
                newsDao.save(*it.data.records.toTypedArray())
                pageLiveData.postValue(it.data)
            } else {
                errorLiveData.postValue(RuntimeException(it.msg))
            }
        }
    }
}